Index: Lib/test/test_fileio.py =================================================================== --- Lib/test/test_fileio.py (revision 77333) +++ Lib/test/test_fileio.py (working copy) @@ -197,6 +197,17 @@ f.close() self.fail("no error for invalid mode: %s" % bad_mode) + def testTruncate(self): + f = _fileio._FileIO(TESTFN, 'w') + f.write(bytes(bytearray(range(10)))) + self.assertEqual(f.tell(), 10) + f.truncate(5) + self.assertEqual(f.tell(), 10) + self.assertEqual(f.seek(0, os.SEEK_END), 5) + f.truncate(15) + self.assertEqual(f.tell(), 5) + self.assertEqual(f.seek(0, os.SEEK_END), 15) + def testTruncateOnWindows(self): def bug801631(): # SF bug Index: Modules/_fileio.c =================================================================== --- Modules/_fileio.c (revision 77333) +++ Modules/_fileio.c (working copy) @@ -647,6 +647,7 @@ fileio_truncate(PyFileIOObject *self, PyObject *args) { PyObject *posobj = NULL; + PyObject *oldposobj = NULL; Py_off_t pos; int ret; int fd; @@ -666,25 +667,21 @@ if (posobj == NULL) return NULL; } - else { - /* Move to the position to be truncated. */ - posobj = portable_lseek(fd, posobj, 0); - } -#if defined(HAVE_LARGEFILE_SUPPORT) - pos = PyLong_AsLongLong(posobj); -#else - pos = PyLong_AsLong(posobj); -#endif - if (PyErr_Occurred()) - return NULL; +#ifdef MS_WINDOWS -#ifdef MS_WINDOWS /* MS _chsize doesn't work if newsize doesn't fit in 32 bits, so don't even try using it. */ { HANDLE hFile; + oldposobj = portable_lseek(fd, NULL, 1); // we save the file pointer position + if (oldposobj == NULL) + return NULL; + posobj = portable_lseek(fd, posobj, 0); // we must move to the truncation position + if (posobj == NULL) + return NULL; + /* Truncate. Note that this may grow the file! */ Py_BEGIN_ALLOW_THREADS errno = 0; @@ -696,12 +693,26 @@ errno = EACCES; } Py_END_ALLOW_THREADS + + oldposobj = portable_lseek(fd, oldposobj, 0); // we restore the file pointer position + if (oldposobj == NULL) + return NULL; } #else + +#if defined(HAVE_LARGEFILE_SUPPORT) + pos = PyLong_AsLongLong(posobj); +#else + pos = PyLong_AsLong(posobj); +#endif + if (PyErr_Occurred()) + return NULL; + Py_BEGIN_ALLOW_THREADS errno = 0; ret = ftruncate(fd, pos); Py_END_ALLOW_THREADS + #endif /* !MS_WINDOWS */ if (ret != 0) {